package highscore;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.FileNotFoundException; 
import java.io.File; 
import java.io.Writer; 
import exceptions.NullArgumentsException;

public class SimpleWriteRead {

	public static String getContents(File aFile) {
		StringBuilder contents = new StringBuilder();
		try {
			BufferedReader input = new BufferedReader(new FileReader(aFile));
			try {
				String line = null;
				while ((line = input.readLine()) != null) {
					contents.append(line);
					contents.append(System.getProperty("line.separator"));
				}
			} finally {
				input.close();
			}
		} catch (IOException ex) {
			ex.printStackTrace();
		}
		return contents.toString();
	}

	public static void setContents(File fileLog, String fileEntry)
			throws FileNotFoundException, IOException {
		if (fileLog == null) {
			throw new IllegalArgumentException("File should not be null.");
		}
		if (!fileLog.exists()) {
			throw new FileNotFoundException("File does not exist: " + fileLog);
		}
		if (!fileLog.isFile()) {
			throw new IllegalArgumentException("Should not be a directory: " + fileLog);
		}
		if (!fileLog.canWrite()) {
			throw new IllegalArgumentException("File cannot be written: " + fileLog);
		}
		Writer output = new BufferedWriter(new FileWriter(fileLog));
		try {
			output.write(fileEntry);
		} finally {
			output.close();
		}
		try {
			if (fileEntry == null) {
				throw new NullArgumentsException("File entry is invalid");
			}
		} catch (NullArgumentsException e) {
			getContents(fileLog);
		}
	}

}